<?php

namespace app\admin\controller;

use app\common\controller\Backend;
//use think\Db;
//use app\admin\library\Auth;


use app\admin\library\Auth;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;



/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Answer extends Backend
{
    
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['tab'];
    /**
     * Answer模型对象
     * @var \app\admin\model\Answer
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Answer;
        $this->view->assign("qstatusList", $this->model->getQstatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $id = $this->auth->id;
            $quanxian = Db::name('auth_group_access')->where('uid',$id)->find();
            if($quanxian['group_id']>2){
                $sql='adminid = '.$id;
            }else{
                $sql='adminid > 0';
            }
           

            $total = $this->model
                    ->where($sql)
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($sql)
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','user','question_id','question','content','qstatus','ip','createtime']);
                
            }
            $list = collection($list)->toArray();
            //dump($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function tab(){

            $id = $this->auth->id;
            $quanxian = Db::name('auth_group_access')->where('uid',$id)->find();
            if($quanxian['group_id']>2){
                $sql='adminid = '.$id;
            }else{
                $sql='adminid > 0';
            }

        $param =$this->request->param();
        if(!empty($param['qid'])){
            $list = Db::name('answer')->where('question_id','=',$param['qid'])->where($sql)->select();
            //return($list);
            if(sizeof($list)>0){
                $this->createcsv($list);
            }else{
                $this->error('没有数据');
            }

        }

        
    }


    public function createcsv($csv_body)
    {
        // 头部标题

        $csv_zhong = array();
        foreach ($csv_body as $key => $value) {
            
            if(!in_array( $value['question'],$csv_zhong)){
                array_push($csv_zhong, $value['question']);
            }
        }


        //$csv_header = array('ID','用户ID','栏目','问题','答案','状态','ip',"创建时间");

        $csv_qian = array('用户ID','栏目');

        $csv_hou = array('ip',"创建时间");

        $csv_header = array_merge($csv_qian,$csv_zhong,$csv_hou);

        $new=array();
        foreach ($csv_body as $k => $v) {
            $new[$v['user']]['id']=$v['id'];
            $new[$v['user']]['question_id']=$v['question_id'];

            foreach ($csv_zhong as $wk => $wen) {
                foreach ($csv_body as $key => $val) {
                    if($wen==$val['question'] && $v['user']==$val['user']){
                        if(strlen($val['content'])>0){
                            $new[$v['user']][$wen]=$val['content'];
                        }else{
                            $new[$v['user']][$wen]="";
                        }
                        
                    }
                }
                if(empty($new[$v['user']][$wen]))$new[$v['user']][$wen]="";
            }

           $new[$v['user']]['ip']=$v['ip'];
           $new[$v['user']]['createtime']=date("Y-m-d H:i:s",$v['createtime']);
        }

        

       
        /**
         * 开始生成
         * 1. 首先将数组拆分成以逗号（注意需要英文）分割的字符串
         * 2. 然后加上每行的换行符号，这里建议直接使用PHP的预定义
         * 常量PHP_EOL
         * 3. 最后写入文件
         */
    // 打开文件资源，不存在则创建
        $des_file = './assets/csv/res.csv';
         unlink($des_file);
        $fp = fopen(    $des_file,'a');
    // 处理头部标题
        $header = implode(',', $csv_header) . PHP_EOL;
    // 处理内容
        $content = '';
        foreach ($new as $klist => $v) {

        $content .= implode(',', $v) . PHP_EOL;
            
            
        }
    // 拼接
        $csv = $header.$content;
    // 写入并关闭资源
        fwrite($fp, $csv);
        fclose($fp);

        $this->redirect($this->request->domain()."/".$des_file);
//           Header("Location: ".$this->request->domain()."/".$des_file); 
           dump($this->request->domain()."/".$des_file.time());
       
//        $this->rec
    }

}
